import base64
import json

from requests import Response
from appstoreserverlibrary.api_client import APIError, APIException, AppStoreServerAPIClient, GetTransactionHistoryVersion
from appstoreserverlibrary.models.AccountTenure import AccountTenure
from appstoreserverlibrary.models.AutoRenewStatus import AutoRenewStatus
from appstoreserverlibrary.models.ConsumptionRequest import ConsumptionRequest
from appstoreserverlibrary.models.ConsumptionStatus import ConsumptionStatus
from appstoreserverlibrary.models.DeliveryStatus import DeliveryStatus
from appstoreserverlibrary.models.Environment import Environment
from appstoreserverlibrary.models.ExpirationIntent import ExpirationIntent
from appstoreserverlibrary.models.ExtendReasonCode import ExtendReasonCode
from appstoreserverlibrary.models.ExtendRenewalDateRequest import ExtendRenewalDateRequest
from appstoreserverlibrary.models.InAppOwnershipType import InAppOwnershipType
from appstoreserverlibrary.models.LastTransactionsItem import LastTransactionsItem
from appstoreserverlibrary.models.LifetimeDollarsPurchased import LifetimeDollarsPurchased
from appstoreserverlibrary.models.LifetimeDollarsRefunded import LifetimeDollarsRefunded
from appstoreserverlibrary.models.MassExtendRenewalDateRequest import MassExtendRenewalDateRequest
from appstoreserverlibrary.models.NotificationHistoryRequest import NotificationHistoryRequest
from appstoreserverlibrary.models.NotificationHistoryResponseItem import NotificationHistoryResponseItem
from appstoreserverlibrary.models.NotificationTypeV2 import NotificationTypeV2
from appstoreserverlibrary.models.OfferType import OfferType
from appstoreserverlibrary.models.OrderLookupStatus import OrderLookupStatus
from appstoreserverlibrary.models.Platform import Platform
from appstoreserverlibrary.models.PlayTime import PlayTime
from appstoreserverlibrary.models.PriceIncreaseStatus import PriceIncreaseStatus
from appstoreserverlibrary.models.RefundPreference import RefundPreference
from appstoreserverlibrary.models.RevocationReason import RevocationReason
from appstoreserverlibrary.models.SendAttemptItem import SendAttemptItem
from appstoreserverlibrary.models.SendAttemptResult import SendAttemptResult
from appstoreserverlibrary.models.Status import Status
from appstoreserverlibrary.models.SubscriptionGroupIdentifierItem import SubscriptionGroupIdentifierItem
from appstoreserverlibrary.models.Subtype import Subtype
from appstoreserverlibrary.models.TransactionHistoryRequest import Order, ProductType, TransactionHistoryRequest
from appstoreserverlibrary.models.TransactionReason import TransactionReason
from appstoreserverlibrary.models.Type import Type
from appstoreserverlibrary.models.UserStatus import UserStatus
from appstoreserverlibrary import signed_data_verifier
from appstoreserverlibrary.models import JWSTransactionDecodedPayload

from tests.util import decode_json_from_signed_date, read_data_from_binary_file, read_data_from_file

from io import BytesIO


def pad_base64_string(base64_str):
    # 计算缺少的等号数量
    missing_padding = 4 - len(base64_str) % 4
    if missing_padding == 4:
        return base64_str

    # 用等号补全字符串
    return base64_str + '=' * missing_padding


def decode_base64_string(base64_str):
    # 补充并解码base64字符串
    padded_str = pad_base64_string(base64_str)
    return base64.b64decode(padded_str)


def test_refund_consum(api_client, transaction_id):
    """
    发送用户消费信息
    :param api_client:
    :return:
    """
    print("开始发送用户消费信息**********************************")
    request = ConsumptionRequest(
        customerConsented=True,
        consumptionStatus=ConsumptionStatus.PARTIALLY_CONSUMED,
        platform=Platform.APPLE,
        sampleContentProvided=True,
        deliveryStatus=DeliveryStatus.DELIVERED_AND_WORKING_PROPERLY,
        appAccountToken='2FA8374C-1592-49EC-BD7A-442FFD6A8871',
        accountTenure=AccountTenure.THIRTY_DAYS_TO_NINETY_DAYS,
        playTime=PlayTime.ONE_DAY_TO_FOUR_DAYS,
        lifetimeDollarsRefunded=LifetimeDollarsRefunded.FIFTY_DOLLARS_TO_NINETY_NINE_DOLLARS_AND_NINETY_NINE_CENTS,
        lifetimeDollarsPurchased=LifetimeDollarsPurchased.FIVE_HUNDRED_DOLLARS_TO_NINE_HUNDRED_NINETY_NINE_DOLLARS_AND_NINETY_NINE_CENTS,
        userStatus=UserStatus.LIMITED_ACCESS,
        refundPreference=RefundPreference.PREFER_DECLINE
    )
    res = api_client.send_consumption_data(transaction_id=transaction_id, consumption_request=request)
    print("========================================================\n", res)

def test_query_transitions(api_client, transaction_id):
    """
    查询历史订单
    :param api_client:
    :return:
    """
    print("开始查询**********************************")
    request = TransactionHistoryRequest(
        sort=Order.ASCENDING,
        # productTypes=[ProductType.CONSUMABLE, ProductType.AUTO_RENEWABLE],
        # endDate=1722580380000, #2024/08/02
        # startDate=1714492800000, #2024/05/01
        revoked=False,
        # inAppOwnershipType=InAppOwnershipType.FAMILY_SHARED,
        # productIds=['recharge_13600'],
        # subscriptionGroupIdentifiers=['sub_group_id', 'sub_group_id_2']
    )
    res = api_client.get_transaction_history(transaction_id=transaction_id, revision=None,
                                             transaction_history_request=request,
                                             version=GetTransactionHistoryVersion.V2)
    transactions = res.signedTransactions
    for item in transactions:
        elements = item.split('.')
        needStr = elements[1]
        json_str = decode_base64_string(needStr)
        itemDict = json.loads(json_str)
        print("========================================================\n", itemDict)

def test_query_oneinfo(api_client, transaction_id):
    """
    查询一个交易订单
    :param api_client:
    :return:
    """
    print("开始查询**********************************")
    res = api_client.get_transaction_info(transaction_id=transaction_id)
    transaction = res.signedTransactionInfo
    print(transaction)
    elements = transaction.split('.')
    needStr = elements[1]
    json_str = decode_base64_string(needStr)
    itemDict = json.loads(json_str)
    print("========================================================\n", itemDict)


def testAA():
    import base64

    # Base64编码的字符串
    base64_string = 'MIIEMDCCA7agAwIBAgIQfTlfd0fNvFWvzC1YIANsXjAKBggqhkjOPQQDAzB1MUQwQgYDVQQDDDtBcHBsZSBXb3JsZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9ucyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTELMAkGA1UECwwCRzYxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTMB4XDTIzMDkxMjE5NTE1M1oXDTI1MTAxMTE5NTE1MlowgZIxQDA+BgNVBAMMN1Byb2QgRUNDIE1hYyBBcHAgU3RvcmUgYW5kIGlUdW5lcyBTdG9yZSBSZWNlaXB0IFNpZ25pbmcxLDAqBgNVBAsMI0FwcGxlIFdvcmxkd2lkZSBEZXZlbG9wZXIgUmVsYXRpb25zMRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEFEYe/JqTqyQv/dtXkauDHCScV129FYRV/0xiB24nCQkzQf3asHJONR5r0RA0aLvJ432hy1SZMouvyfpm26jXSjggIIMIICBDAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFD8vlCNR01DJmig97bB85c+lkGKZMHAGCCsGAQUFBwEBBGQwYjAtBggrBgEFBQcwAoYhaHR0cDovL2NlcnRzLmFwcGxlLmNvbS93d2RyZzYuZGVyMDEGCCsGAQUFBzABhiVodHRwOi8vb2NzcC5hcHBsZS5jb20vb2NzcDAzLXd3ZHJnNjAyMIIBHgYDVR0gBIIBFTCCAREwggENBgoqhkiG92NkBQYBMIH+MIHDBggrBgEFBQcCAjCBtgyBs1JlbGlhbmNlIG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBjb25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZpY2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMDYGCCsGAQUFBwIBFipodHRwOi8vd3d3LmFwcGxlLmNvbS9jZXJ0aWZpY2F0ZWF1dGhvcml0eS8wHQYDVR0OBBYEFAMs8Pjs6VhWGQlzE2ZOE+GX4Oo/MA4GA1UdDwEB/wQEAwIHgDAQBgoqhkiG92NkBgsBBAIFADAKBggqhkjOPQQDAwNoADBlAjEA8yRNdskp506DFdPLghLLJwAv5J8hBGLaI8DExdcPX+aBKjjO8eUo9KpfpcNYUY5YAjAPXmMXEZL+Q02adrmmshNxz3NnKm+ouQwU7vBTn0LvlM7vps2YslVTamRYL4aSs5k='

    # 解码Base64字符串
    decoded_data = base64.b64decode(base64_string)

    # 将解码后的数据写入文件
    with open('cert.pem', 'wb') as file:
        file.write(decoded_data)

    # 使用OpenSSL命令行工具转换证书
    import subprocess

    subprocess.run(['openssl', 'x509', '-in', 'cert.pem', '-outform', 'der', '-out', 'cert.der'])


class MYClass(object):
    @staticmethod
    def test():
        pass

    def test1(self):
        pass

    def __init__(self):
        self.name = ""
        self._age = 10

if __name__ == "__main__":
    with open("AuthKey_5B9NM4U4A2.p8", "rb") as f:
        bytes = f.read()
    api_client = AppStoreServerAPIClient(signing_key=bytes,
                                         key_id="5B9NM4U4A2",
                                         bundle_id="com.wooyee.hlah",
                                         issuer_id="f82f228d-f3d5-4831-b609-b673d8f1f120",
                                         environment=Environment.SANDBOX)
    #查询历史交易订单
    # test_query_transitions(api_client, transaction_id="2000000678468810")

    #查询单笔交易订单
    test_query_oneinfo(api_client, transaction_id="2000000696802384")

    #发送用户消费信息
    # test_refund_consum(api_client, transaction_id="2000000679559844")

    # testAA()
